package com.xiyu.service.dal.websocket.downloadMailHeader;

import com.xiyu.service.dal.websocket.downloadMailHeader.message.DownloadMailHeaderReceiverMessage;
import com.xiyu.service.enums.common.UserTypeEnum;
import com.xiyu.service.framework.exception.ServiceException;
import com.xiyu.service.framework.postOffice.factory.PostOfficeFactory;
import com.xiyu.service.framework.postOffice.service.PostOfficeService;
import com.xiyu.service.framework.websocket.core.listener.WebSocketMessageListener;
import com.xiyu.service.framework.websocket.core.sender.WebSocketMessageSender;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import jakarta.annotation.Resource;

import static com.xiyu.service.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Component
public class DownloadMailHeaderWebSocketMessageListener implements WebSocketMessageListener<Long> {
    @Resource
    private WebSocketMessageSender webSocketMessageSender;

    @Resource
    private PostOfficeFactory postOfficeFactory;

    final String socketType = "download-mail-header";

    @Override
    public void onMessage(WebSocketSession session, Long accountId) {
        try {
            PostOfficeService postOfficeService = postOfficeFactory.getInstance(accountId);
            postOfficeService.downloadAccountMailHeader();
        }catch (ServiceException e){
            DownloadMailHeaderReceiverMessage toMessage = new DownloadMailHeaderReceiverMessage(e.getMessage(), "error", 0, 0);
            webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(), getLoginUserId(),
                    "download-mail-header", toMessage);
        }
    }

    @Override
    public String getType() {
        return socketType;
    }
}
